<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2022-12-30 16:14:56
 * @Last Modified time: 2023-02-23 10:30:51
 */

namespace app\common\services\store;

use app\common\dao\store\DiyPageDao;

use frank\base\BaseService;
use frank\exception\CommonException;
use frank\utils\helper\ArrayHelper;
use frank\services\CacheService;

/**
 * Class DiyPageService
 * 缓存文件
 */
class DiyPageService extends BaseService
{

    public $cacheKey = "store:diy_page:";

    /**
     * DiyPageService constructor.
     * @param DiyPageDao $dao
     */
    public function __construct(DiyPageDao $dao)
    {
        $this->dao = $dao;
    }

    public function getDiyPageDetail($param)
    {
        $filter = [];
        if (is_array($param)) {
            $filter = $param;
        } else {
            $filter['id'] = (int)$param;
        }
        $detail = $this->dao->search($filter)->find();
        if (!$detail) {
            throw new CommonException('数据不存在');
        }
        $detail = $detail->toArray();
        return $detail;
    }

    /**
     * 获取列表
     */
    public function getDiyPageList(array $params)
    {
        [$page, $limit] = $this->getPageValue();
        $where = [];
        $list = $this->dao->getDiyPageList($where, $page, $limit);
        return $list;
    }

    /**
     * 获取首页
     */
    public function getHome(){
        $detail = CacheService::instance()->get($this->cacheKey.'home');
        if(!$detail){
            $detail = $this->dao->search(['is_home'=>1])->find();
            if (!$detail) {
                throw new CommonException('首页未设置');
            }
            $detail = $detail->toArray();
            if(empty($detail['page_data']) || $detail['page_data']== null){
                throw new CommonException('首页未设置');
            }
            CacheService::instance()->set($this->cacheKey.'home',$detail);
        }
        return $detail;
    }

    /**
     * 设置为首页
     */
    public function setHome($pid){
        $status = $this->transaction(function($query) use ($pid){
            $this->dao->update(['is_home'=>1],['is_home'=> 0]);
            $this->dao->update($pid,['is_home'=> 1]);
            return true;
        });
        return $status;
    }

    /**
     * 删除缓存
     */
    public function deleteCache(){
        CacheService::instance()->delete($this->cacheKey.'home');
    }
}